package com.luhuiguo.cms.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.luhuiguo.cms.server.entity.Channel;
import com.luhuiguo.cms.server.entity.User;
import com.luhuiguo.cms.server.service.ChannelService;
import com.luhuiguo.cms.server.service.UserService;
import com.luhuiguo.cms.shared.model.Role;

@Controller
public class PublishController {

    @Autowired
    private UserService userService;

    @Autowired
    private ChannelService channelService;

    @RequestMapping("/")
    public String welcomeHandler() {
        return "index";
    }

    @RequestMapping("/login")
    public ModelAndView loginHandler(
            @RequestParam(value = "failed", required = false, defaultValue = "false") boolean failed) {
        ModelAndView mav = new ModelAndView("login");

        mav.addObject("failed", failed);

        return mav;
    }

    @RequestMapping("/init")
    public String initHandler() {
        if (userService.findUsers().size() < 1) {
            User userAdmin = new User("admin", "manager", "Administrator", Role.ROLE_ADMIN);
            userService.saveUser(userAdmin);
        }
        System.out.println(userService.findUsers());

        if (channelService.findChannels().size() < 1) {
            Channel root = new Channel(null, "home", "home", "首页");
            channelService.saveChannel(root);
            Channel c1 = new Channel(root.getId(), "home/news", "news", "新闻");
            channelService.saveChannel(c1);
            Channel c2 = new Channel(root.getId(), "home/sports", "sports", "体育");
            channelService.saveChannel(c2);

        }
        System.out.println(channelService.findChannels());

        return "index";
    }

    @RequestMapping("/*.html")
    public void defaultHandler() {

    }

}
